/**
    @project {
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:maven:0.1-SNAPSHOT",
            "org.helgoboss:scala-additions:0.1-SNAPSHOT",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT"
        ]
    }
*/

package org.helgoboss.maven_ref_impl

import sys.process._
import org.helgoboss.maven.Maven
import java.io.File
import org.helgoboss.scala_additions.Implicits._
import org.helgoboss.scala_additions.CurrentPlatform
import org.helgoboss.scala_additions.OperatingSystemClass._
import org.helgoboss.osgi_additions._
import org.helgoboss.osgi_additions.metatype._

class Activator extends OsgiProvider with OsgiConfigurationWatcher with OsgiMetaTypeProvider {
    whenBundleActive {        
        provideMetaType(objectClass)
        
        whenConfigurationUpdated(objectClass.id) { conf =>
            val resultConf = conf match {
                case Some(c) => objectClass.defaultConfig ++ c
                case None => objectClass.defaultConfig
            }
            val exeFile = new File(resultConf("exeFile").asInstanceOf[String])
            new MavenRefImpl(exeFile = exeFile).providesService[Maven]
        }
    }
    
    lazy val objectClass = ObjectClass (
        id = "org.helgoboss.maven",
        name = "Maven",
        optionalAttributes = List (
            ElementaryAttribute[String](id = "exeFile", name = "Maven executable path", default = Some(MavenRefImpl.defaultExeFile.getPath))
        )
    )
    
}

object MavenRefImpl {
    lazy val defaultExeFile = new File(
        CurrentPlatform.osClass match {
            case Windows => "mvn.bat"
            case Unix => "mvn"
        }
    )
}

class MavenRefImpl(exeFile: File = MavenRefImpl.defaultExeFile) extends Maven {
    def prepareExecution(baseDir: File, arguments: Seq[String] = Nil) = {
        Process(command = List(exeFile.osDependentPathExpression) ++ arguments, cwd = baseDir)
    }
}